import { defineEventHandler, getQuery, readBody } from 'h3'
import { query, execute } from '../utils/db'
import { hash, verify } from 'argon2'
import dayjs from 'dayjs'
import { customAlphabet } from 'nanoid'
import mysql from 'mysql2'

const alphabet = '123456789abcdefghijklmnopqrstuvwxyz'
const nanoid = customAlphabet(alphabet, 10)

interface User {
  user_id: string
  username: string
  disable?: number
  role?: string
  role_id?: number
  create_time?: string
}

export default defineEventHandler(async (event) => {
  const method = event.node.req.method
  // 用户注册
  if (method === 'POST' && event.path?.endsWith('/register')) {
    const body = await readBody(event)
    const { username, password } = body

    // 参数验证
    if (!username || !password) {
      throw createError({
        statusCode: 400,
        message: 'Username and password are required'
      })
    }

    // 检查用户名是否已存在
    const checkSql = 'SELECT user_id FROM user WHERE username = ? LIMIT 1'
    const { results: [existingUser] } = await query(checkSql, [username])

    if (existingUser) {
      throw createError({
        statusCode: 400,
        message: 'Username already exists'
      })
    }

    const hashedPassword = await hash(password)
    const time = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const id = nanoid()

    // 插入用户
    const insertSql = `
      INSERT INTO user 
      (user_id, username, password, create_time, role_id) 
      VALUES (?, ?, ?, ?, ?)
    `
    await execute(insertSql, [id, username, hashedPassword, time, 0])

    // 返回用户信息
    const { results: [user] } = await query<mysql.RowDataPacket[]>(
      `SELECT u.user_id, u.username, r.role 
       FROM user u LEFT JOIN role r ON u.role_id = r.role_id 
       WHERE u.user_id = ? LIMIT 1`,
      [id]
    )

    return {
      status: 'success',
      data: user
    }
  }

  // 用户登录
  if (method === 'POST' && event.path?.endsWith('/login')) {
    const body = await readBody(event)
    const { username, password } = body

    // 参数验证
    if (!username || !password) {
      throw createError({
        statusCode: 400,
        message: 'Username and password are required'
      })
    }

    // 查询用户
    const sql = `
      SELECT 
        u.user_id, u.username, u.password, u.disable, 
        r.role_id, r.role 
      FROM user u 
      LEFT JOIN role r ON u.role_id = r.role_id 
      WHERE u.username = ? 
      LIMIT 1
    `
    const { results: [user] } = await query<mysql.RowDataPacket[]>(sql, [username])

    if (!user) {
      throw createError({
        statusCode: 401,
        message: 'Invalid credentials'
      })
    }

    // 验证密码
    if (!(await verify(user.password, password))) {
      throw createError({
        statusCode: 401,
        message: 'Invalid credentials'
      })
    }

    if (user.disable) {
      throw createError({
        statusCode: 403,
        message: 'Account disabled'
      })
    }

    // 返回用户信息但不包含密码
    const { password: _, ...userWithoutPassword } = user
    return {
      status: 'success',
      data: userWithoutPassword
    }
  }

  // 获取用户列表
  if (method === 'GET' && event.path?.endsWith('/users')) {
    console.log('Fetching users list')
    const queryParams = getQuery(event)
    const page = Number(queryParams.page) || 1
    const size = Number(queryParams.size) || 10

    // 参数验证
    if (page < 1 || size < 1) {
      throw createError({
        statusCode: 400,
        message: 'Invalid pagination parameters'
      })
    }

    const sql = `
      SELECT 
        u.user_id, u.username, u.create_time, u.disable, 
        r.role_id, r.role 
      FROM user u 
      LEFT JOIN role r ON u.role_id = r.role_id 
      ORDER BY u.create_time DESC 
      LIMIT ?, ?
    `
    const { results: users } = await query<mysql.RowDataPacket[]>(sql, [
      (page - 1) * size,
      size
    ])

    // 获取总数
    const countSql = 'SELECT COUNT(*) as total FROM user'
    const { results: [{ total }] } = await query<mysql.RowDataPacket[]>(countSql)

    return {
      status: 'success',
      data: users,
      pagination: {
        total,
        currentPage: page,
        perPage: size,
        totalPages: Math.ceil(total / size)
      }
    }
  }

  // 获取单个用户
  if (method === 'GET' && event.path?.includes('/users/')) {
    console.log('Fetching single user')
    const id = event.context.params?.id
    if (!id) {
      throw createError({
        statusCode: 400,
        message: 'User ID is required'
      })
    }

    const sql = `
      SELECT 
        u.user_id, u.username, u.disable, 
        r.role_id, r.role 
      FROM user u 
      LEFT JOIN role r ON u.role_id = r.role_id 
      WHERE u.user_id = ? 
      LIMIT 1
    `
    const { results: [user] } = await query<mysql.RowDataPacket[]>(sql, [id])

    if (!user) {
      throw createError({
        statusCode: 404,
        message: 'User not found'
      })
    }

    return {
      status: 'success',
      data: user
    }
  }

  // 禁用/启用用户
  if (method === 'PATCH' && event.path?.includes('/users/') && event.path?.endsWith('/disable')) {
    const id = event.context.params?.id
    if (!id) {
      throw createError({
        statusCode: 400,
        message: 'User ID is required'
      })
    }

    const body = await readBody(event)
    const disable = body.disable !== undefined ? Number(body.disable) : 1

    const sql = 'UPDATE user SET disable = ? WHERE user_id = ? LIMIT 1'
    await execute(sql, [disable, id])

    // 返回更新后的用户信息
    const { results: [user] } = await query<mysql.RowDataPacket[]>(
      `SELECT u.user_id, u.username, u.disable, r.role 
       FROM user u LEFT JOIN role r ON u.role_id = r.role_id 
       WHERE u.user_id = ? LIMIT 1`,
      [id]
    )

    return {
      status: 'success',
      data: user
    }
  }

  // 未匹配的路由
  throw createError({
    statusCode: 404,
    message: 'Endpoint not found'
  })
})